<template>
    <div>
        <header>
            <div class="topWrapper">
                <div class="item" v-for="(i,index) in orderTimeMap" :key="i">
                    <el-form ref="validateFormOuter" label-width="58px" :size="customStyle.size" class="outerForm"
                             :model="sendFormData" :rules="useRule(index)">
                        <span class="text-color2">{{i}}</span>
                        <el-form-item label="商家" :prop="`platform.${index}`">
                            <el-select v-model="sendFormData.platform[index]" placeholder="请选择商家" clearable>
                                <el-option
                                    v-for="i in platformData"
                                    :key="i.value"
                                    :label="i.label"
                                    :value="i.value">
                                </el-option>
                            </el-select>
                            <el-image
                                v-show="showImgList(index).length"
                                ref="elImage"
                                :preview-src-list="showImgList(index)">
                                <i slot="error" @click="clickHandler(index)" class="iconfont icon-diancandingdan0101"></i>
                            </el-image>
                        </el-form-item>
                        <el-form-item :prop="`remark`" label-width="30px">
                            <span class="text-color3" v-if="isUseName(index)">起送价{{useResult[index].step}}，可在名称后面"()"里添加备注，{{isShopUse(index)?'多个逗号分隔，例：麻辣小龙虾(加辣),大闸蟹(少辣)':'A1(加辣)'}}</span>
                            <span class="text-color3" v-else>起送价{{useResult[index].step}}，可在CODE后面"()"里添加备注，{{isShopUse(index)?'多个逗号分隔，例：A1(加辣),A2(少辣)':'A1(加辣)'}}</span>
                        </el-form-item>
                        <template v-if="!isShopUse(index)">
                            <div class="orderItem" v-for="j in orderMenus[i].filter(i=>i!==null)">
                                <!--`code.${index}.${j}` `name.${index}.${j}` `price.${index}.${j}`-->
                                <el-form-item v-if="sendFormData.code[index] && !isUseName(index)" :prop="`code.${index}.${j}`"
                                              label="CODE">
                                    <el-input clearable v-model="sendFormData.code[index][j]" placeholder="A1"
                                              autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item :prop="`name.${index}.${j}`" label="名称">
                                    <el-input clearable v-model="sendFormData.name[index][j]" placeholder="麻辣小龙虾"
                                              autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item :prop="`price.${index}.${j}`" label="价格">
                                    <el-input clearable type="number" v-model.number="sendFormData.price[index][j]"
                                              placeholder="1680"
                                              autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item label-width="0">
                                    <el-button type="primary" plain icon="el-icon-plus"
                                               @click="handlePlus(i,j)"></el-button>
                                    <el-button type="primary" plain icon="el-icon-minus"
                                               @click="handleMinus(i,j)"></el-button>
                                </el-form-item>
                            </div>
                        </template>
                        <div class="orderItem shopUseItem" v-else>
                            <el-form-item v-if="!isUseName(index)" :label="`CODE`" :prop="`onlyCode.${index}`">
                                <el-input clearable v-model="sendFormData.onlyCode[index]"
                                          placeholder="A1,A2" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label-width="51px" v-else :label="`名称`" :prop="`onlyName.${index}`">
                                <el-input clearable v-model="sendFormData.onlyName[index]"
                                          placeholder="麻辣小龙虾,大闸蟹" autocomplete="off"></el-input>
                            </el-form-item>
                        </div>
                    </el-form>
                </div>
                <div>
                    <el-button :size="customStyle.size" type="primary" @click="handleSave(0)">保 存</el-button>
                    <el-button :size="customStyle.size" plain @click="handleClear()">取 消</el-button>
                </div>
            </div>
            <div class="topInfoWrap">
                <el-button v-if="userInfo.authBtn.includes('/order/changeTogether')" icon="el-icon-plus" type="primary"
                           :size="customStyle.size" @click="changeTogether('',true)">新增订单
                </el-button>
                <el-button v-if="userInfo.authBtn.includes('/order/viewBtn')"
                           type="primary"
                           :size="customStyle.size" @click="orderDialog"> 生成统计信息
                </el-button>
            </div>
        </header>
        <el-dialog :append-to-body="true"
                   :close-on-click-modal="false"
                   title="统计信息"
                   :visible.sync="orderInfoVisible"
                   width="80%"
        >
            <template v-for="(v,k) in orderInfo">
                <el-divider content-position="left">{{orderTimeMap[k]}}</el-divider>
                <div class="orderInfoWrap">
                    <div v-for="info in Object.values(v)" class="textItem">
                        <el-button class="copyItem" icon="el-icon-document-copy" @click="copyInfo"
                                   :data-clipboard-text="info.join('\n')" type="text">复制
                        </el-button>
                        <el-input
                            type="textarea"
                            disabled
                            :rows="12"
                            :value="info.join('\n')">
                        </el-input>
                    </div>
                </div>
            </template>
        </el-dialog>
        <order-info :orderData="tableData" :platformData="platformData" :tableSlots="tableSlots">
            <template #handle="scope">
                <div v-if="scope.row.code || scope.row.name" class="controlBth">
                    <el-button size="mini" type="primary" plain
                               @click="scope.row.senduser?changeTogether(scope.row,true):copyOrder(scope.row,scope.row.username===userInfo.username || scope.row.operateUser === userInfo.username)">
                        {{scope.row.username === userInfo.username || scope.row.operateUser === userInfo.username ? '编辑' : '复制'}}
                    </el-button>
                    <el-button size="mini" type="primary" plain
                               @click="getLogs(scope.row.username,scope.row.logs)">
                        查看记录
                    </el-button>
                    <!-- 点餐完毕进行审核 -->
                    <template v-if="scope.row.isAudit.some(i=>!i) && scope.row.status">
                        <el-button v-if="userInfo.authBtn.includes('/order/pass')" size="mini" type="primary" plain
                                   @click="checkDialog(scope.row,1)">
                            {{$i18n.t('btnControl./order.pass')}}
                        </el-button>
                        <el-button v-if="userInfo.authBtn.includes('/order/refuse')" size="mini" type="primary" plain
                                   @click="checkDialog(scope.row,0)">
                            {{$i18n.t('btnControl./order.refuse')}}
                        </el-button>
                    </template>
                    <el-button v-if="userInfo.authBtn.includes('/order/setStatus')" size="mini" type="danger" plain
                               @click="changeStatus(scope.row.username,scope.row.status?0:1)">
                        {{$i18n.t('btnControl./order.setStatus')[scope.row.status]}}
                    </el-button>
                    <el-button v-if="userInfo.authBtn.includes('/order/changeTogether') && !scope.row.senduser"
                               size="mini" type="primary" plain
                               @click="changeTogether(scope.row,true)">
                        {{$i18n.t('btnControl./order.changeTogether')}}
                    </el-button>
                </div>
            </template>
        </order-info>
        <el-dialog :append-to-body="true"
                   :close-on-click-modal="false"
                   :before-close="(done)=>{isTransform=false;done()}"
                   :title="checkOrder.title"
                   v-if="checkOrder.visible"
                   :visible.sync="checkOrder.visible"
                   width="90%"
        >
            <el-form ref="checkFormInner" label-width="80px" :size="customStyle.size" class="innerForm"
                     :model="checkData" :rules="rulesCheck">
                <div class="top">
                    <el-form-item label="用户名" :prop="(checkData.senduser || isTransform)?'senduser':'username'">
                        <el-select v-if="checkData.senduser || isTransform" :disabled="!isTransform" v-model="checkData.senduser" multiple
                                   placeholder="请选择拼单用户">
                            <el-option
                                v-for="i in userList"
                                :key="i"
                                :label="i"
                                :value="i">
                            </el-option>
                        </el-select>
                        <el-input v-else :disabled="!isTransform" clearable v-model="checkData.username" placeholder="请输入用户名"
                                  autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item :prop="`remark`" v-if="checkData.senduser" label-width="30px">
                        <span class="text-color3">已选择{{checkData.senduser.length}}个用户，<span class="notice">订单类型为{{checkData.senduser.length>1?'拼团订单':'代点订单'}}</span></span>
                    </el-form-item>
                </div>
                <!--`code.${index}.${j}` `name.${index}.${j}` `price.${index}.${j}`-->
                <div class="bottom">
                    <div class="item" v-for="(i,index) in orderTimeMap" :key="i">
                        <el-form ref="validateFormInner" label-width="90px" :size="customStyle.size" class="innerForm"
                                 :model="checkData" :rules="useCheckRule(index)">
                            <span class="text-color2">{{i}}</span>
                            <el-form-item label-width="70px" label="商家" :prop="`platform.${index}`">
                                <el-select :disabled="!isTransform" v-model="checkData.platform[index]" placeholder="请选择商家" clearable>
                                    <el-option
                                        v-for="i in platformData"
                                        :key="i.value"
                                        :label="i.label"
                                        :value="i.value">
                                    </el-option>
                                </el-select>
                                <el-image
                                    v-show="showImgList(index).length"
                                    ref="elImage"
                                    :preview-src-list="showImgList(index)">
                                    <i slot="error" @click="clickHandler(index)" class="iconfont icon-diancandingdan0101"></i>
                                </el-image>
                            </el-form-item>
                            <el-form-item :prop="`remark`" label-width="30px">
                                <span class="text-color3" v-if="isUseName(index)">起送价{{useResult[index].step}}，可在名称后面"()"里添加备注，{{isShopUse(index)?'多个逗号分隔，例：麻辣小龙虾(加辣),大闸蟹(少辣)':'A1(加辣)'}}</span>
                                <span class="text-color3" v-else>起送价{{useResult[index].step}}，可在CODE后面"()"里添加备注，{{isShopUse(index)?'多个逗号分隔，例：A1(加辣),A2(少辣)':'A1(加辣)'}}</span>
                            </el-form-item>
                            <template v-if="!isShopUse(index)">
                                <div class="orderItem" v-for="j in checkOrder.orderMenus[i].filter(i=>i!==null)">
                                    <!--`code.${index}.${j}` `name.${index}.${j}` `price.${index}.${j}`-->
                                    <el-form-item v-if="checkData.code[index] && !isUseName(index)" :prop="`code.${index}.${j}`"
                                                  label="CODE">
                                        <el-input :disabled="!isTransform" clearable v-model="checkData.code[index][j]" placeholder="A1"
                                                  autocomplete="off"></el-input>
                                    </el-form-item>
                                    <el-form-item label-width="80px" :prop="`name.${index}.${j}`" label="名称">
                                        <el-input :disabled="!!isUseName(index) && !isTransform" clearable v-model="checkData.name[index][j]" placeholder="麻辣小龙虾"
                                                  autocomplete="off"></el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`price.${index}.${j}`" label="价格">
                                        <el-input :disabled="!isTransform" clearable type="number" v-model.number="checkData.price[index][j]"
                                                  placeholder="1680"
                                                  autocomplete="off"></el-input>
                                    </el-form-item>
                                    <el-form-item label-width="0">
                                        <el-button type="primary" plain icon="el-icon-plus"
                                                   @click="handlePlus(i,j)"></el-button>
                                        <el-button type="primary" plain icon="el-icon-minus"
                                                   @click="handleMinus(i,j)"></el-button>
                                    </el-form-item>
                                </div>
                            </template>
                            <div class="orderItem shopUseItem" v-else>
                                <el-form-item v-if="!isUseName(index)" :label="`CODE`" :prop="`onlyCode.${index}`">
                                    <el-input :disabled="!isTransform" clearable v-model="checkData.onlyCode[index]"
                                              placeholder="A1,A2" autocomplete="off"></el-input>
                                </el-form-item>
                                <el-form-item label-width="51px" v-else :label="`名称`" :prop="`onlyName.${index}`">
                                    <el-input :disabled="!isTransform" clearable v-model="checkData.onlyName[index]"
                                              placeholder="麻辣小龙虾,大闸蟹" autocomplete="off"></el-input>
                                </el-form-item>
                            </div>
                        </el-form>
                    </div>
                </div>
                <el-form-item class="refruseInfo" v-if="!isTransform && !checkOrder.type" label="备注" prop="msg">
                    <el-input clearable v-model="checkData.msg" placeholder="请输入审核失败原因"
                              autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :size="customStyle.size" @click="checkOrder.visible = false">取 消</el-button>
                <el-button :size="customStyle.size" type="primary" @click="!isTransform?handleCheck():saveOrder()">
                    {{!isTransform?(checkOrder.type ? "通 过" : "拒 绝"):'确 定'}}
                </el-button>
            </div>
        </el-dialog>
        <el-dialog :append-to-body="true"
                   :close-on-click-modal="false"
                   :title="logsDailog.title"
                   :visible.sync="logsDailog.visible"
                   width="70%"
        >
            <el-table
                :data="logsDailog.logsData"
                border
                stripe
            >
                <el-table-column
                    prop="create_time"
                    width="100px"
                    label="时间">
                </el-table-column>
                <el-table-column
                    prop="input"
                    min-width="100px"
                    label="创建订单">
                    <template #default="scope">
                        <div class="logInfo" v-html="scope.row.input"></div>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="output"
                    min-width="200px"
                    label="生成订单">
                    <template #default="scope">
                        <div class="logInfo" v-html="scope.row.output"></div>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import {getTag} from '@/api/tag'
import {setOrder, getOrder, setOrderStatus, orderCountDown, refuseOrder, passOrder} from '@/api/order'
import {getFood} from '@/api/food'
import Clipboard from 'clipboard'
import tableMixin from '@/mixins/table'
import {mapGetters} from 'vuex'
import moment from "moment";
import {getUser} from '@/api/user'

const evil = window.eval;
import pick from 'lodash/pick'
import isUndefined from 'lodash/isUndefined'
import isString from 'lodash/isString'
import isNull from 'lodash/isNull'
import cloneDeep from 'lodash/cloneDeep'
import difference from 'lodash/difference'
import sortBy from 'lodash/sortBy'
import isArray from 'lodash/isArray'
import flatten from 'lodash/flatten'
import compact from 'lodash/compact'
import concat from 'lodash/concat'
import set from 'lodash/set'
import get from 'lodash/get'
import OrderInfo from '@/components/order-info'
import {getFoodImg} from '@/api/food'
const validateCode = (rule, value, callback) => {
    if (!/^[a-zA-Z\d]+$/.test(value)) {
        console.log(value)
        callback(new Error('CODE只能输入字母和数字'));
    } else {
        callback();
    }
}
export default {
    name: "home",
    mixins: [tableMixin],
    components: {
        OrderInfo
    },
    data() {
        return {
            shopImgList:[],
            orderInfoVisible: false,
            orderInfo: {},
            totalPrice: {},
            checkOrder: {
                type: 1,
                visible: false,
                orderMenus: {},
                title: '订单审核'
            },
            isTransform: false,
            tableSlots: [
                {
                    prop: 'handle',
                    label: '操作',
                    minWidth: '60px'
                }
            ],
            logsDailog: {
                logsData: [],
                visible: false,
                title: '',
            },
            copyItem: {},
            orderMenus: {},
            dialogVisible: false,
            platformData: [],
            sendFormData: {
                senduser: '',
                note: '',
                operateUser: '',
                platform: [],
                username: '',
                onlyCode: [],
                onlyName: [],
                code: [],
                name: [],
                price: []
            },
            checkData: {
                senduser: '',
                note: '',
                operateUser: '',
                msg: '',
                platform: [],
                username: '',
                onlyCode: [],
                onlyName: [],
                code: [],
                name: [],
                price: []
            },
            rulesCheck: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                ],
                senduser: [
                    {required: true, message: '请选择拼单用户', trigger: 'blur'},
                ],
            },
            rules: {
                senduser: [
                    {required: true, message: '请选择拼单用户', trigger: 'blur'},
                ],
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                ],
                platform: [
                    {required: true, message: '请选择商家', trigger: 'change'},
                ],
                name: [
                    {required: true, message: '请输入菜单名称', trigger: 'blur'},
                ],
                price: [
                    {required: true, message: '请输入菜单价格', trigger: 'blur'},
                ],
                onlyCode: [
                    {required: true, message: '请输入菜单CODE', trigger: 'blur'}
                ],
                onlyName: [
                    {required: true, message: '请输入菜单名称', trigger: 'blur'}
                ],
                code: [
                    {required: true, message: '请输入菜单CODE', trigger: 'blur'},
                ]
            },
            rulesStrict: {}
        }
    },
    created() {
        getFoodImg().then(res => {
            this.shopImgList = res.data
        })
        this.getTag({type: 0})
        this.orderTimeMap.map((i, index) => {
            this.$set(this.orderInfo, index, {});
            this.$set(this.totalPrice, index, {});
            ['rulesStrict','rulesCheck'].map(k=>{
                this.$set(this[k], `onlyCode.${index}`, [{
                    required: true,
                    message: '请输入菜单CODE，多个逗号分隔',
                    trigger: 'blur'
                }])
                this.$set(this[k], `platform.${index}`, [{
                    required: true,
                    message: '请选择商家',
                    trigger: 'change'
                }])
                this.$set(this[k], `onlyName.${index}`, [{
                    required: true,
                    message: '请输入菜单名称，多个逗号分隔',
                    trigger: 'blur'
                }])
            });
        })
        this.initSendFormData(true)
        //引用值无法清除
        this.sendFormData.username = this.userInfo.username
        this.checkData.username = this.userInfo.username
    },
    computed: {
        showImgList(){
            return (index=0)=>{
                const platform = this.checkOrder.visible?this.checkData.platform:this.sendFormData.platform;
                return this.shopImgList.filter(i=>i.includes(platform[index])).map(i=>this.domainUrl+i)
            }
        },
        useResult() {
            const platform = this.checkOrder.visible?this.checkData.platform:this.sendFormData.platform;
            return this.orderTimeMap.map((i,index)=>platform[index]?this.platformData.find(i => i.value === platform[index]):{isReady: 0, type: 0,step:0})
        },
        isShopUse() {
            return (index=0)=>{
                return this.useResult[index].isReady
            }
        },
        isUseName() {
            return (index=0)=>{
                return this.useResult[index].type
            }
        },
        orderParamsMap() {
            return (index=0)=>{
                return ['code', 'price', 'name'].filter(k => this.isUseName(index) ? k !== 'code' : true)
            }
        },
        ...mapGetters([
            'userList',
            'statusData',
            'orderTimeMap',
            'countDown',
            'orderTimeControl',
            'ioAwaitTime',
            'userOrder',
            'orderStatusInfo'
        ])
    },
    watch: {
        orderStatusInfo(v) {
            this.getTableData()
        }
    },
    methods: {
        evil,
        useCheckRule(index){
            const rules=this.rulesCheck
            this.$nextTick(()=>{
                this.orderTimeMap.map((i, index) => {
                    this.$refs.validateFormInner[index].clearValidate()
                })
            })
            return this.isUseName(index) ?
                pick(rules, Object.keys(rules).filter(k => {
                    const realK=k.split('.')[0]
                    if(this.isShopUse(index)){
                        return ['platform','onlyName'].includes(realK)
                    }else {
                        return ['platform','name','price'].includes(realK)
                    }
                })):
                pick(rules, Object.keys(rules).filter(k => {
                    const realK=k.split('.')[0]
                    if(this.isShopUse(index)){
                        return ['platform','onlyCode'].includes(realK)
                    }else {
                        const isAll=this.checkOrder.type && !this.isTransform
                        const checkKey=isAll?['platform','name','code','price']:['platform','code','price']
                        return checkKey.includes(realK)
                    }
                }));
        },
        useRule(index,isClear){
            const rules=this.rulesStrict
            this.$nextTick(()=>{
                this.orderTimeMap.map((i, index) => {
                    this.$refs.validateFormOuter[index].clearValidate()
                })
            })
            return this.isUseName(index) ?
            pick(rules, Object.keys(rules).filter(k => {
                const realK=k.split('.')[0]
                if(this.isShopUse(index)){
                    return ['platform','onlyName'].includes(realK)
                }else {
                    return ['platform','name','price'].includes(realK)
                }
            })):
            pick(rules, Object.keys(rules).filter(k => {
                const realK=k.split('.')[0]
                if(this.isShopUse(index)){
                    return ['platform','onlyCode'].includes(realK)
                }else {
                    const checkKey=isClear?['platform','name','code','price']:['platform','code','price']
                    return checkKey.includes(realK)
                }
            }));
        },
        clickHandler(index){
            this.$refs.elImage[index].clickHandler()
            this.$nextTick(()=>{
                document.querySelector('.el-image-viewer__wrapper').setAttribute('style','z-index:9999;');
            })
        },
        orderDialog() {
            // this.userList
            const userList = this.tableData.map(item => (item.code || item.name) && (item.senduser ? item.senduser : item.username))
            const remainUser = difference(this.userList, flatten(compact(userList)))
            Object.keys(this.orderInfo).map(k => {
                this.orderInfo[k] = {}
                this.totalPrice[k] = {}
            })
            if (remainUser.length) {
                this.showConfirm(`${remainUser.join(',')}未点餐，是否继续生成统计信息？`).then(() => {
                    this.tableData.filter(i=>i.platform).map(item => {
                        this.formatInfo(item)
                    })
                    Object.keys(this.orderInfo).map(k => {
                        Object.keys(this.orderInfo[k]).map(plat=>{
                            this.orderInfo[k][plat].push(`合计  ${this.totalPrice[k][plat]}`)
                        });
                    });
                    this.orderInfoVisible = true
                })
            } else {
                const totalPrice = {};
                this.tableData.filter(i=>i.platform).map(item => {
                    this.formatInfo(item)
                })
                Object.keys(this.orderInfo).map(k => {
                    Object.keys(this.orderInfo[k]).map(plat=>{
                        console.log(plat,'plat')
                        this.orderInfo[k][plat].push(`合计  ${this.totalPrice[k][plat]}`)
                    });
                });
                this.orderInfoVisible = true
            }
        },
        formatInfo(data) {
            data.platform = data.platform.filter(i=>i);
            data.platform.map((plat,index)=>{
                const totalPrice=this.totalPrice[index];
                const orderObj = this.orderInfo[index];
                const isUseName = (this.platformData.find(i => i.value === plat) || {type: 0}).type;
                (isUseName ? data.name : data.code)[index].split(',').map((v, vIndex) => {
                    const noteIndex = (data.note || []).findIndex(i => i.includes(v));
                    const vPrice = data.price[index].split(',')[vIndex]
                    if (!orderObj[plat]) {
                        totalPrice[plat] = Number(vPrice);
                        if (noteIndex > -1) {
                            v = data.note[noteIndex]
                        }
                        const platformName = (this.platformData.find(i => i.value === plat) || {label: '未知商家'}).label
                        this.$set(orderObj, plat, [`${platformName}`, `${v}*1  ${vPrice}*1  `])
                    } else {
                        const findIndex = orderObj[plat].findIndex(i => i.includes(`${v}*`) && i.includes(`${vPrice}*`));
                        if (findIndex > -1 && noteIndex < 0) {
                            const match = orderObj[plat][findIndex].match(new RegExp('(?<=\\*)\\d+'));
                            const num = Number(match && match[0] || 0) + 1;
                            totalPrice[plat] = totalPrice[plat] + vPrice * (num - 1);
                            const replaceStr = orderObj[plat][findIndex].replace(/\*\d+/g, `*${num}`);
                            orderObj[plat].splice(findIndex, 1, replaceStr);
                        } else {
                            if (noteIndex > -1) {
                                v = data.note[noteIndex]
                            }
                            totalPrice[plat] = totalPrice[plat] + Number(vPrice);
                            orderObj[plat].push(`${v}*1  ${vPrice}*1  `)
                        }
                    }
                })
            })
        },
        handleClear(noReset, done) {
            this.orderTimeMap.map((i,index)=>{
                Object.keys(this.useRule(index,true)).map(k=>{
                    set(this.sendFormData,k,"")
                })
                this.orderMenus[i] = [0]
            })
            this.$forceUpdate();
            done && done();
            this.dialogVisible = false
        },
        handleCheck() {
            const realSendFormData = {};
            const sendFormData=this.checkData
            realSendFormData.note = sendFormData.note
            realSendFormData.name = isArray(sendFormData.name) && sendFormData.name.map(i=>i.join(','));
            realSendFormData.code = isArray(sendFormData.code) && sendFormData.code.map(i=>i.join(','));
            realSendFormData.price = isArray(sendFormData.price) && sendFormData.price.map(i=>i.join(','));
            realSendFormData.platform = sendFormData.platform
            realSendFormData.username = sendFormData.username
            realSendFormData.operateUser = sendFormData.operateUser
            realSendFormData.msg = sendFormData.msg;
            const realOrderInfo=this.orderTimeMap.map((i,index)=>realSendFormData.platform[index] && i).filter(i=>i)
            Promise.all(this.checkOrder.visible?
                concat(realOrderInfo.map((item,index)=>{
                    return new Promise(resolve=>{
                        this.$refs.validateFormInner[index].validate(valid => resolve(valid))
                    })
                }),[new Promise(resolve=>{
                    this.$refs.checkFormInner.validate(valid => resolve(valid))
                })]):
                realOrderInfo.map((item,index)=>{
                    return new Promise(resolve=>{
                        this.$refs.validateFormOuter[index].validate(valid => resolve(valid))
                    })
                })
            ).then(valid=>{
                if(!valid.some(i=>!i)){
                    if (this.checkOrder.type) {
                        passOrder(realSendFormData).then(res => {
                            this.$message.success(res.msg)
                            this.checkOrder.visible = false;
                            this.getTableData()
                        })
                    } else {
                        refuseOrder(realSendFormData).then(res => {
                            this.$message.success(res.msg)
                            this.checkOrder.visible = false;
                            this.getTableData()
                        })
                    }
                }
            })
        },
        checkDialog(item, type) {
            this.isTransform = false
            this.checkOrder.type = type;
            this.checkOrder.visible = true;
            this.copyOrder(item,true)
        },
        changeTogether(item, isTransform = false) {
            this.isTransform = isTransform;
            if(isTransform || item.senduser){
                this.checkOrder.title=item?'转换订单':'新增订单'
                this.checkOrder.visible = true
            }
            this.initSendFormData(true)
            item && this.copyOrder(item,true)
        },
        copyOrder(item, isEdit) {
            //拒绝订单拒绝不验证名字
            item.price=isArray(item.price) && item.price.filter(v=>v!=='0')
            if(isArray(item.code)){
                item.code=item.code.map(v=>{
                    const index=(item.note || []).findIndex(i=>i.includes(v))
                    if(index>-1){
                        v=item.note[index]
                    }
                    return v
                }).filter(v=>v)
            }
            if(isArray(item.name)){
                item.name=item.name.map(v=>{
                    const index=(item.note || []).findIndex(i=>i.includes(v))
                    if(index>-1){
                        v=item.note[index]
                    }
                    return v
                }).filter(v=>v)
            }
            const sendFormData=this.checkOrder.visible?this.checkData:this.sendFormData
            const rules=this.checkOrder.visible?this.rulesCheck:this.rulesStrict
            const orderMenus=this.checkOrder.visible?this.checkOrder.orderMenus:this.orderMenus
            sendFormData.senduser = cloneDeep(item.senduser)
            sendFormData.platform = cloneDeep(item.platform)
            sendFormData.operateUser = !isEdit?this.userInfo.username:item.operateUser
            sendFormData.username = !isEdit?this.userInfo.username:item.username
            const msg = {code: 'CODE', price: '价格', name: '名称'}
            this.orderTimeMap.map((t, index) => {
                if(this.isShopUse(index)){
                    this.isUseName(index) ? (sendFormData.onlyName = cloneDeep(item.name)) :
                        (sendFormData.onlyCode = cloneDeep(item.code));
                }else {
                    const dataLen=this.isUseName(index)?item.name.length:item.code.length
                    this.orderParamsMap(index).map(k => {
                        this.$set(sendFormData[k],index,cloneDeep(item[k][index] ? item[k][index].split(','):new Array(dataLen).fill('')))
                        orderMenus[t] = []
                        sendFormData[k][index].map((v, vIndex) => {
                            this.$set(orderMenus[t], vIndex, vIndex)
                            this.$set(rules, `${k}.${index}.${vIndex}`, [{
                                required: true,
                                message: `请输入菜单${msg[k]}`,
                                trigger: 'blur'
                            }])
                        })
                    })
                }
            })
            !isEdit && this.saveOrder(item.senduser)
        },
        getLogs(username, data) {
            this.logsDailog.logsData = data
            this.logsDailog.visible = true
            this.logsDailog.title = `${username}点餐记录`
        },
        initSendFormData(isInit) {
            const msg = {code: 'CODE', price: '价格', name: '名称'}
            const sendFormData=this.checkOrder.visible?this.checkData:this.sendFormData
            sendFormData.senduser=""
            const rules=this.checkOrder.visible?this.rulesCheck:this.rulesStrict
            const orderMenus=this.checkOrder.visible?this.checkOrder.orderMenus:this.orderMenus
            if (isInit) {
                this.orderTimeMap.map((i, index) => {
                    sendFormData.platform[index]=""
                    //清空掉sendFormData
                    this.orderParamsMap().map(k => {
                        if (sendFormData[k][index]) {
                            if (index) {
                                delete sendFormData[k][index]
                            } else {
                                sendFormData[k][index] = []
                            }
                        }
                    })
                    orderMenus[i] = [0]
                })
            }
            Object.values(orderMenus).map((item, index) => {
                this.orderParamsMap(index).map(k => {
                    !sendFormData[k][index] && (this.$set(sendFormData[k], index, []))
                    item.map(j => {
                        if (isNull(j)) {
                            delete rules[`${k}.${index}.${j}`]
                            sendFormData[k][index][j] = null
                        } else {
                            this.$set(rules, `${k}.${index}.${j}`, [{
                                required: true,
                                message: `请输入菜单${msg[k]}`,
                                trigger: 'blur'
                            }])
                            if (!sendFormData[k][index][j]) {
                                sendFormData[k][index][j] = ''
                            }
                        }
                    })
                });
            })
        },
        handlePlus(i) {
            const orderMenus=this.checkOrder.visible?this.checkOrder.orderMenus:this.orderMenus
            const index = orderMenus[i].length - 1
            orderMenus[i].push(index + 1)
            this.initSendFormData()
            this.$forceUpdate()
        },
        handleMinus(i, index) {
            const orderMenus=this.checkOrder.visible?this.checkOrder.orderMenus:this.orderMenus
            if (orderMenus[i].filter(i => i !== null).length === 1) return;
            orderMenus[i].splice(index, 1, null)
            this.initSendFormData()
            this.$forceUpdate()
        },
        getTag(data) {
            getTag(data).then(res => {
                this.platformData = res.data
            })
        },
        copyInfo() {
            const clipboard = new Clipboard('.copyItem')
            clipboard.on('success', e => {
                this.$message.success('复制成功')
                // 释放内存
                clipboard.destroy()
            })
            clipboard.on('error', e => {
                this.$message.success('复制失败')
                clipboard.destroy()
            })
        },
        tableCallback() {
            //保证订单状态一直刷新
            this.tableData.map(async item => {
                if(!isUndefined(item.status)){
                    if(!item.status){
                        await this.setCountDown(item.username)
                        const startTime = this.orderTimeControl.startTime
                        const seconds = (new Date()).getTime() - startTime
                        const durationTime = moment.duration(seconds).seconds()
                        //相差秒数
                        const remainTime = this.orderTimeControl.orderTimeLimit - durationTime * 1000
                        remainTime >= 0 && this.$store.commit('exclude/SET_COUNT_DOWN', remainTime)
                    }else {
                        this.userOrder[item.username] && this.$store.commit('exclude/SET_HAD_USER',[item.username,0])
                    }
                }
            });
        },
        rowSaveApi:setOrder,
        tableApi: getOrder,
        async setCountDown(senduser) {
            if(!this.userOrder[senduser]){
                await setTimeout(async () => {
                    await orderCountDown({senduser}).then(res => {
                        const {orderTimeLimit, startTime} = res.data
                        this.$store.commit('system/SET_ORDER_TIME_LIMIT', {orderTimeLimit, startTime})
                        this.$store.commit('exclude/SET_HAD_USER',[senduser,1])
                    })
                }, this.ioAwaitTime)
            }
        },
        changeStatus(senduser, status) {
            setOrderStatus({username:this.userInfo.username,senduser, status}).then(res => {
                this.$message.success(res.msg)
                this.getTableData()
            })
        },
        async saveOrder(type, noReset) {
            const sendFormData=this.checkOrder.visible?this.checkData:this.sendFormData
            let realSendFormData = {};
            realSendFormData.note = sendFormData.note || []
            realSendFormData.name = [];
            realSendFormData.code = [];
            realSendFormData.price = [];
            realSendFormData.platform = sendFormData.platform
            realSendFormData.username = sendFormData.username
            realSendFormData.operateUser = sendFormData.operateUser || sendFormData.username
            if (sendFormData.senduser) {
                //多人点餐
                if(sendFormData.senduser.length===1){
                    realSendFormData.username=sendFormData.senduser[0]
                }else {
                    realSendFormData.senduser = sendFormData.senduser
                }
            }
            if(!realSendFormData.platform.filter(i=>i).length) return;
            const realOrderInfo=this.orderTimeMap.map((i,index)=>realSendFormData.platform[index] && i).filter(i=>i)
            Promise.all(this.checkOrder.visible?
                concat(realOrderInfo.map((item,index)=>{
                    return new Promise(resolve=>{
                        this.$refs.validateFormInner[index].validate(valid => resolve(valid))
                    })
                }),[new Promise(resolve=>{
                    this.$refs.checkFormInner.validate(valid => resolve(valid))
                })]):
                realOrderInfo.map((item,index)=>{
                    return new Promise(resolve=>{
                        this.$refs.validateFormOuter[index].validate(valid => resolve(valid))
                    })
                })
            ).then(valid=>{
                if(!valid.some(i=>!i)){
                    const warnMsg=this.orderTimeMap.map((i,index)=>{
                        if(this.isShopUse(index)){
                            if(this.isUseName(index)){
                                sendFormData.onlyName[index] = sendFormData.onlyName[index].replace(/，/g, ',').replace(/\s/g, "")
                                realSendFormData.name[index] = sendFormData.onlyName[index].split(',').map(n => {
                                    if (/\([^\)]*\)/g.test(v) || /\（[^\）]*\）/g.test(v)) {
                                        realSendFormData.note.push(n);
                                        n = n.replace(/\([^\)]*\)/g, '').replace(/\（[^\）]*\）/g, '');
                                    }
                                    return n
                                }).join(',')
                            }else {
                                sendFormData.onlyCode[index] = sendFormData.onlyCode[index].replace(/，/g, ',').replace(/\s/g, "")
                                realSendFormData.code[index] = sendFormData.onlyCode[index].split(',').map(n => {
                                    if (/\([^\)]*\)/g.test(n) || /\（[^\）]*\）/g.test(n)) {
                                        realSendFormData.note.push(n);
                                        n = n.replace(/\([^\)]*\)/g, '').replace(/\（[^\）]*\）/g, '');
                                    }
                                    return n.toUpperCase()
                                }).join(',')
                            }
                        }else {
                            this.orderParamsMap(index).map(k => {
                                realSendFormData[k][index] = sendFormData[k][index].slice(0, this.orderMenus[i].filter(j => j !== null).length).filter(j => j).map(v => {
                                    // /(?<=\()[^)]*(?=\))/g
                                    if (/\([^\)]*\)/g.test(v) || /\（[^\）]*\）/g.test(v)) {
                                        realSendFormData.note.push(v);
                                        v = v.replace(/\([^\)]*\)/g, '').replace(/\（[^\）]*\）/g, '');
                                    }
                                    return v && String(v).toUpperCase()
                                }).join(',')
                            });
                        }
                        return !(this.isUseName(index)?realSendFormData.name[index]:realSendFormData.code[index]) && i
                    }).filter(i=>i).join(',')
                    if (warnMsg) {
                        this.showConfirm(`${warnMsg}信息未填写，是否提交？`).then(() => {
                            this.rowSave(realSendFormData).then(res => {
                                this.handleClear(noReset)
                                this.checkOrder.visible = false
                            })
                        })
                    } else {
                        this.rowSave(realSendFormData).then(res => {
                            this.handleClear(noReset)
                            this.checkOrder.visible = false
                        })
                    }
                }
            })
        },
        handleSave(type) {
            if (type) {
                this.$refs.validateFormInner.validate((valid) => {
                    if (valid) {
                        this.saveOrder(type)
                    }
                })
            } else {
                this.saveOrder()
            }
        }
    }
}
</script>

<style scoped lang="scss">
.topWrapper {
    flex-wrap:wrap;
    display:flex;
    &:empty {
        display:none;
    }
    .left {
        display:flex;
    }
    margin-bottom:20px;
}

>>> .el-image {
    cursor: pointer;
    margin-left:15px;
    .iconfont {
        font-size:28px;
        color: $theme-color;
    }
}
.orderInfoWrap {
    display:flex;
    .textItem {
        flex:0 0 33%;
        position:relative;
        > .el-button {
            position:absolute;
            right:0;
            top:0;
            padding-right:10px;
            padding-left:10px;
            z-index:9;
        }
        > > > .el-textarea.is-disabled .el-textarea__inner {
            color:#333;
            line-height:25px;
        }
    }
}
> > > .logInfo {
    span {
        padding:0 2px;
        &:empty {
            padding:0 !important;
        }
    }
    .remark {
        &:empty {
            display:none;
        }
    }

}
.shopUseItem {
    >>> .el-input {
        width: 650px!important;
    }
}
.orderItem {
    display:flex;
    align-items:center;
    flex-wrap:wrap;
    min-width:80%;
    margin-top:15px;
    &:nth-of-type(1) {
        margin-top:0 !important;
        margin-left:0 !important;
    }
}
header {
    .text-color2 {
        margin-right:10px;
    }
}
.orderItem {
    margin-left:50px;
}
.innerForm {
    .refruseInfo {
        >>> .el-input {
            width:500px!important;
        }
    }
    .top {
        display: flex;
        margin-bottom:15px;
        >>> .el-select .el-input, >>> .el-input{
            width:500px!important;
        }
        .notice {
            color:#F56C6C ;
        }
    }
    .text-color2 {
        //padding-left:10px;
        display: block;
        width:58px;
        font-size:15px;
        text-align: right;
        /*&:before{
            content: '*';
            color: #F56C6C;
            margin-right: 4px;
        }*/
    }
}
.item {
    margin-bottom:20px;
    display:flex;
    align-items:center;
    flex-wrap:wrap;
    .el-button {
        margin-left:20px !important;
    }
    .text-color2 {
        line-height:36px;
        flex:none;
    }
}
.orderCode {
    width:80%;
    .el-input {
        margin:0 20px;
    }
    > span {
        flex:none;
    }
}
.topInfoWrap {
    display:flex;
    justify-content:space-between;
}
> > > .balanceInfoWrap {
    p {
        margin:8px 0 !important;
    }
}
/*.innerForm {
    .orderItem {
        margin-left:30px;
        margin-top:20px;
        flex-wrap:nowrap;
    }
    .item {
        flex-wrap:wrap;
        display:flex;
        margin-bottom:20px;
    }
    .bottom {
        padding-left:30px;
        .text-color2 {
            width:30px;
            text-align:center;
            flex:none;
            line-height:30px;
        }
        .orderItem {
            > * {
                margin-bottom:0;
            }
            .el-button {
                margin-left:15px;
            }
        }
        .el-input {
            width:180px;
        }
    }
}*/
.el-table {
    margin-top:20px;
}


</style>
